<?php


namespace App\Http\Controllers\OaManagement;

use App\Http\Controllers\admin\BranchController;
use App\Http\Controllers\BranchUtils;
use App\Http\Controllers\common\CommonFun;
use App\Http\Controllers\common\LMReturn;
use App\Models\BankCard;
use App\Models\CustArea;
use App\Models\Image;
use App\Models\MassageChangeRecord;
use App\Http\Controllers\Controller;
use App\Models\Branch;
use App\Models\FamiliesMoneyRecord;
use App\Models\Order;
use App\Models\User;
use App\Models\Worker;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Utils;
use App\Models\OaModelBranch;
use App\Models\WorkerBranch;
use Illuminate\Http\Request;
use App\Models\OaRecord;
use App\Models\OaModel;
use App\Models\OaFlow;

class OAController extends Controller
{
    // 只能存在唯一类型的模板列表
    const MAXMODEL = [2];
    // 模板的添加+修改+删除+查询
    public function OAModel(Request $request)
    {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $operation_id = $tokenInfo['worker_id'];
        $is_allow = Utils::OAPer($operation_id);
        if ($is_allow != true) {
            // 现在无权限判断，若要加权限可以在权限表和角色-权限表加新数据和绑定关系来判断是否有权限
            return LMReturn::insertErr($is_allow);
        }
        $all = $request->all();
        if (empty($all['bm_id_list'])) {
            $bm_id = WorkerBranch::where('worker_id', $operation_id)->first()->branch_id;
            $bm_list[] = $bm_id;
        } else {
            $bm_list = $all['bm_id_list'];
        }
        if (empty($all['model'])) {
            return LMReturn::Error('未传入操作模式');
        } else {
            // 添加
            if ($all['model'] == 1) {
                if (empty($all['name'])) {
                    return LMReturn::insertErr('未传入表单名称');
                }
                if (empty($all['group'])) {
                    return LMReturn::insertErr('未传入分组');
                }
                if (in_array($all['group'], OAController::MAXMODEL)) {
                    if (env('COMPANY') != 3) {
                        $models = OaModel::where('group', $all['group'])->first();
                        if (isset($models)) {
                            return LMReturn::Error('无法添加，该类型模板已存在，并且只能存在一个');
                        }
                    } else {
                        $branchs = Branch::whereIn('id', $bm_list)->get();
                        foreach ($branchs as $item) {
                            if ($item['pid'] != 1) {
                                return LMReturn::Error('该部门没有生成该模板权限');
                            }
                        }
                        $models = OaModel::where('group', 2)->with('branches')->get();
                        foreach ($models as $model) {
                            if ($model['branches']) {
                                foreach ($model['branches'] as $branch) {
                                    if (in_array($branch['id'], $bm_list)) {
                                        return LMReturn::Error('添加失败，部门-' . $branch['name'] . '-已有此类型模板');
                                    }
                                }
                            }
                        }
                    }
                }
                DB::beginTransaction();                                 // 开启数据库事务
                try {
                    $new_model = new OaModel();
                    $new_model->name = $all['name'];
                    $new_model->group = $all['group'];
                    $new_model->content = empty($all['content']) ? '' : $all['content'];
                    $new_model->save();
                    $new_model->branches()->sync($bm_list);
                } catch (\Throwable $th) {
                    DB::rollback();             // 数据库回滚
                    return LMReturn::updateErr();
                }
                DB::commit();
                return LMReturn::Success([], '添加成功');
            } elseif ($all['model'] == 2) {
                // 修改
                if (empty($all['model_id'])) {
                    return LMReturn::Error('未传入模型id');
                }
                DB::beginTransaction();                                 // 开启数据库事务
                try {
                    $up_model = OaModel::where('id', $all['model_id'])->first();
                    if (empty($up_model)) {
                        return LMReturn::Error('没有该模型');
                    }
                    if (isset($all['name'])) {
                        $up_model->name = $all['name'];
                    }
                    if (isset($all['group'])) {
                        $up_model->group = $all['group'];
                    }
                    if (isset($all['content'])) {
                        $up_model->content = $all['content'];
                    }
                    $up_model->save();
                    $up_model->branches()->sync($bm_list);
                } catch (\Throwable $th) {
                    DB::rollback();             // 数据库回滚
                    return LMReturn::updateErr();
                }
                DB::commit();
                return LMReturn::Success([], '修改成功');
            } elseif ($all['model'] == 3) {
                // 删除
                if (empty($all['model_id'])) {
                    return LMReturn::Error('未传入模型id');
                }
                $dele_model = OaModel::where('id', $all['model_id'])->first();
                if (empty($dele_model)) {
                    return LMReturn::Error('没有该模型');
                } else {
                    $oa_flow = OaFlow::where('oa_model_id', $all['model_id'])->get();
                    $oa_branch = OaModelBranch::where('oa_model_id', $all['model_id'])->get();
                    foreach ($oa_flow as $flow) {
                        $flow->delete();
                    }
                    foreach ($oa_branch as $branch) {
                        $branch->delete();
                    }
                    $dele_model->delete();
                }
                return LMReturn::Success([], '删除成功');
            } else {
                $workers = Worker::where('id', $operation_id)->with('branches')->first();
                if (isset($workers['branches'])) {
                    $branch_lists = $this->getBranchChain($workers['branches'][0]['id']);
                } else {
                    return LMReturn::Error('请加入部门');
                }
                if (isset($all['model_id'])) {
                    $models = OaModel::where('id', $all['model_id'])
                        ->with('oa_flows')
                        ->with('oa_flows.worker.branches')
                        ->with('branches')
                        ->first();
                    $data_dic = [];
                    $data_dic['model_id'] = $models['id'];
                    $data_dic['content'] = $models['content'];
                    $data_dic['group'] = $models['group'];
                    $branch_list = [];
                    $sta = 0;
                    foreach ($models['branches'] as $branch) {
                        if (in_array($branch['id'], $branch_lists)) {
                            $sta = 1;
                        }
                        $branch_dic = [];
                        $branch_dic['branch_id'] = $branch['id'];
                        $branch_dic['branch_name'] = $branch['name'];
                        $branch_list[] = $branch_dic;
                    }
                    if ($sta == 0) {
                        return LMReturn::Error('没有权限');
                    }
                    $data_dic['branch_list'] = $branch_list;
                    $flow_list = [];
                    foreach ($models['oa_flows'] as $flows) {
                        $flow_dic = [];
                        $flow_dic['flow_id'] = $flows['id'];
                        $flow_dic['worker_id'] = $flows['worker_id'];
                        $flow_dic['worker_name'] = $flows['worker']['name'];
                        $flow_dic['level'] = $flows['level'];
                        $flow_dic['type'] = $flows['type'];
                        $flow_dic['worker_type'] = $flows['worker_type'];
                        $flow_dic['branch_id'] = $flows['worker']['branches'][0]['id'];
                        $flow_dic['branch_name'] = $flows['worker']['branches'][0]['name'];
                        $flow_list[] = $flow_dic;
                    }
                    $data_lists = array_column($flow_list, 'level');
                    array_multisort($data_lists, SORT_ASC, $flow_list);
                    $data_dic['flow_list'] = $flow_list;
                    return LMReturn::Success($data_dic, '查找成功');
                } else {
                    $models = OaModel::with('branches')->get();
                    $data_list = [];
                    foreach ($models as $model_dic) {
                        $data_dic = [];
                        $data_dic['model_id'] = $model_dic['id'];
                        $data_dic['name'] = $model_dic['name'];
                        $data_dic['content'] = $model_dic['content'];
                        $data_dic['group'] = $model_dic['group'];
                        $branch_list = [];
                        $branchs = [];
                        foreach ($model_dic['branches'] as $branch) {
                            $branch_dic = [];
                            $branchs[] = $branch['id'];
                            $branch_dic['branch_id'] = $branch['id'];
                            $branch_dic['branch_name'] = $branch['name'];
                            $branch_list[] = $branch_dic;
                        }
                        $data_dic['branch_list'] = $branch_list;
                        $data_dic['branchs'] = $branchs;
                        $data_list[] = $data_dic;
                    }
                    $size = $all['size'] ?? 15;
                    $page = $all['page'] ?? 1;
                    $start = ($page - 1) * $size;
                    $article = array_slice($data_list, $start, $size);
                    $datas_list = [];
                    $count = count($data_list);
                    $datas_list['total'] = $count;
                    $datas_list['data'] = $article;
                    return LMReturn::Success($datas_list, '查找成功');
                }
            }
        }
    }

    // 审核流程的添加+修改+删除+查询
    public function OAFlow(Request $request)
    {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $operation_id = $tokenInfo['worker_id'];
        $is_allow = Utils::OAPer($operation_id);
        if (!$is_allow) {
            // 现在无权限判断，若要加权限可以在权限表和角色-权限表加新数据和绑定关系来判断是否有权限
            return LMReturn::insertErr('没有权限！');
        }
        $all = $request->all();
        if (empty($all['model'])) {
            return LMReturn::Error('未传入操作模式');
        } else {
            // 添加
            if ($all['model'] == 1) {
                if (empty($all['model_id'])) {
                    return LMReturn::Error('未传入模型id');
                } else {
                    $model_id = $all['model_id'];
                }
                if (empty($all['worker_id'])) {
                    return LMReturn::insertErr('未传入审核人');
                }
                if (empty($all['p_id'])) {
                    DB::beginTransaction();                                 // 开启数据库事务
                    try {
                        $new_flows = new OaFlow();
                        $new_flows->oa_model_id = $model_id;
                        $new_flows->level = 1;
                        $new_flows->type = $all['type'] ?? 1;
                        $new_flows->worker_id = $all['worker_id'];
                        $new_flows->worker_type = 1;
                        $new_flows->save();
                    } catch (\Throwable $th) {
                        DB::rollback();             // 数据库回滚
                        return LMReturn::updateErr();
                    }
                    DB::commit();
                    return LMReturn::Success([], '添加成功');
                } else {
                    $p_id = $all['p_id'];
                }
                $is_before = empty($all['is_before']) ? 1 : $all['is_before'];  // 1是在p_id之前加入， 2是在p_id之后加入
                if ($is_before == 1) {
                    $oa_flows = OaFlow::find($p_id);
                    if (isset($oa_flows)) {
                        DB::beginTransaction();                                 // 开启数据库事务
                        try {
                            $levels = $oa_flows->level;
                            $new_flows = new OaFlow();
                            if ($oa_flows->p_id == null) {
                                $new_flows->p_id = $oa_flows->p_id;
                            }
                            $new_flows->oa_model_id = $model_id;
                            $new_flows->level = $levels;
                            $new_flows->type = $all['type'] ?? 1;
                            $new_flows->worker_type = 1;
                            $new_flows->worker_id = $all['worker_id'];
                            $new_flows->save();
                            $new_flows_id = $new_flows->id;
                            $oa_flows->p_id = $new_flows_id;
                            $oa_flows->save();
                            $this->up_level(1, $p_id);
                        } catch (\Throwable $th) {
                            DB::rollback();             // 数据库回滚
                            return LMReturn::updateErr();
                        }
                        DB::commit();
                    } else {
                        return LMReturn::Error('未找到传入流程');
                    }
                } else {
                    DB::beginTransaction();                                 // 开启数据库事务
                    try {
                        $oa_flow = OaFlow::where('id', $p_id)->first();
                        $next_flow = OaFlow::where('p_id', $p_id)->first();
                        if (empty($oa_flow)) {
                            return LMReturn::Error('未找到传入流程');
                        }
                        $levels = $oa_flow->level + 1;
                        $new_flows = new OaFlow();
                        $new_flows->p_id = $p_id;
                        $new_flows->oa_model_id = $model_id;
                        $new_flows->level = $levels;
                        $new_flows->type = $all['type'] ?? 1;
                        $new_flows->worker_type = 1;
                        $new_flows->worker_id = $all['worker_id'];
                        $new_flows->save();
                        $new_flows_id = $new_flows->id;
                        if (isset($next_flow)) {
                            $next_flow->p_id = $new_flows_id;
                            $next_flow->save();
                            $this->up_level(1, $next_flow->id);
                        }
                    } catch (\Throwable $th) {
                        DB::rollback();             // 数据库回滚
                        return LMReturn::updateErr();
                    }
                    DB::commit();
                }
                return LMReturn::Success([], '添加成功');
            } elseif ($all['model'] == 2) {
                // 修改
                if (empty($all['flow_id'])) {
                    return LMReturn::updateErr('未传入需要修改的流程');
                }
                $up_flows = OaFlow::where('id', $all['flow_id'])->first();
                if (isset($all['worker_id'])) {
                    $up_flows->worker_id = $all['worker_id'];
                }
                if (isset($all['type'])) {
                    $up_flows->type = $all['type'];
                }
                $up_flows->save();
                return LMReturn::Success([], '修改成功');
            } elseif ($all['model'] == 3) {
                // 删除
                if (empty($all['flow_id'])) {
                    return LMReturn::updateErr('未传入需要删除的流程');
                }
                $dele_flows = OaFlow::where('id', $all['flow_id'])->first();
                $oa_flows = OaFlow::where('p_id', $all['flow_id'])->first();
                if (empty($dele_flows)) {
                    return LMReturn::deleteErr('没有该流程');
                }
                if (isset($oa_flows)) {
                    $oa_flows->p_id = $dele_flows->p_id;
                    $oa_flows->save();
                    $this->up_level(2, $oa_flows->id);
                }
                $dele_flows->delete();
                return LMReturn::Success([], '删除成功');
            } else {
                if (empty($all['flow_id'])) {
                    return LMReturn::selectErr('未传入流程id');
                }
                $flows = OaFlow::where('id', $all['flow_id'])->with('oa_model')->with('worker.branches')->first();
                if (empty($flows)) {
                    return LMReturn::selectErr('未找到该流程id');
                }
                $level = $flows->level;
                if ($level == 1) {
                    $data_list = [];
                    $data_dic = [];
                    $data_dic['flows_id'] = $flows['id'];
                    $data_dic['worker_id'] = $flows['worker_id'];
                    $data_dic['worker_name'] = $flows['worker']['name'] ?? '';
                    $data_dic['branch_id'] = $flows['worker']['branches'][0]['id'] ?? '';
                    $data_dic['branch_name'] = $flows['worker']['branches'][0]['name'] ?? '';
                    $data_dic['oa_model_id'] = $flows['oa_model_id'];
                    $data_dic['model_name'] = $flows['oa_model']['name'];
                    $data_dic['model_group'] = $flows['oa_model']['group'];
                    $data_dic['level'] = $flows['level'];
                    $data_dic['type'] = $flows['type'];
                    $data_dic['worker_type'] = $flows['worker_type'];
                    $data_list[] = $data_dic;
                    $data_list = $this->sele_flow($data_list, $flows['id']);
                    $data_lists = array_column($data_list, 'level');
                    array_multisort($data_lists, SORT_ASC, $data_list);
                    return LMReturn::Success($data_list);
                } else {
                    return LMReturn::selectErr('请输入头id');
                }
            }
        }
    }

    // 审核流程--申请--员工
    public function OAapply(Request $request)
    {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $operation_id = $tokenInfo['worker_id'];
        $worker = Worker::find($operation_id);
        $branch_manage_list = $worker->branches;
        $branch_id = $branch_manage_list[0]['id'];
        $all = $request->all();
        if (empty($all['model'])) {
            return LMReturn::Error('未传入操作模式');
        } else {
            if ($all['model'] == 1) {
                // 提交
                if (isset($all['is_pass']) && $all['is_pass'] != '') {
                    $is_pass = $all['is_pass'] == 5 ? 5 : 4;
                } else {
                    $is_pass = 4;
                }
                if (empty($all['record_id'])) {
                    if (empty($all['flow_id'])) {
                        return LMReturn::insertErr('未传入审核流程');
                    }
                    $flows = OaFlow::find($all['flow_id']);
                    if (empty($flows)) {
                        return LMReturn::insertErr('未找到该流程');
                    } elseif ($flows->level != 1) {
                        return LMReturn::insertErr('请从第一步开始');
                    } else {
                        $branch_lists = OaModel::where('id', $flows->oa_model_id)->with('branches')->first()->branches;
                        $is_can = false;
                        foreach ($branch_lists as $m_branch) {
                            $branch_id_list = Utils::getChildSonBranchs($m_branch->id);
                            foreach ($branch_id_list as $bid) {
                                if ($branch_id == $bid) {
                                    $is_can = true;
                                    break;
                                }
                            }
                            if ($is_can) {
                                break;
                            }
                        }
                        if ($is_can) {
                            return LMReturn::insertErr('非所属部门无法添加');
                        }
                        DB::beginTransaction();                                 // 开启数据库事务
                        try {
                            $groups = OaModel::find($flows->oa_model_id)->group;
                            if ($groups == 2) {
                                return LMReturn::Error('无法直接提交该类型审核');
                            }
                            if ($groups == 1) {
                                if (empty($all['money'])) {
                                    return LMReturn::insertErr('未传入申请金额');
                                }
                                $finance = new FamiliesMoneyRecord();
                                $finance->worker_id = $operation_id;
                                $finance->branch_id = $branch_id;
                                $finance->money = $all['money'];
                                $finance->type = 3;
                                $finance->status = 1;
                                $finance->save();
                                $finance_id = $finance->id;
                            } else {
                                $finance_id = null;
                            }
                            $new_recode_id = $this->create_all_record($all['flow_id'], $all['remark'] ?? '', $operation_id, $branch_id, 1, 4, $finance_id);
                            if ($is_pass == 4) {
                                $recodes = OaRecord::where('id', $new_recode_id)->with('oa_flow')->first();
                                $recodes->is_finally = 2;
                                if ($recodes['oa_flow']['type'] == 2) {
                                    $recodes->is_pass = 3;
                                    $recodes->save();
                                    $this->get_next_flow($new_recode_id, 2);
                                } elseif ($recodes['oa_flow']['type'] == 1) {
                                    $recodes->is_pass = 0;
                                    $recodes->save();
                                }
                            } else {
                                $recodes = OaRecord::find($new_recode_id);
                                $recodes->is_finally = 4;
                                $recodes->save();
                            }
                        } catch (\Throwable $th) {
                            DB::rollback();             // 数据库回滚
                            return LMReturn::updateErr('插入失败');
                        }
                        DB::commit();
                        return LMReturn::Success();
                    }
                } else {
                    DB::beginTransaction();
                    try {
                        $new_recode_id = $all['record_id'];
                        $records = OaRecord::where('id', $new_recode_id)->with('families_money_record')->with('oa_flow')->first();
                        if ($records->is_finally == 4) {
                            $money = $all['money'];
                            $remark = $all['remark'];
                            if ($records->finance_id) {
                                FamiliesMoneyRecord::where('id', $records->finance_id)->update(['money' => $money]);
                            }
                            $records->remark = $remark;
                            $records->save();
                            OaRecord::where('p_id', $records->id)->update(['remark' => $remark]);
                            if ($is_pass == 5) {
                                DB::commit();
                                return LMReturn::Success('草稿已修改');
                            } else {
                                $records->is_finally = 2;
                                if ($records['oa_flow']['type'] == 2) {
                                    $records->is_pass = 3;
                                    $records->save();
                                    $this->get_next_flow($new_recode_id, 2);
                                } elseif ($records['oa_flow']['type'] == 1) {
                                    $records->is_pass = 0;
                                    $records->save();
                                }
                                DB::commit();
                                return LMReturn::Success();
                            }
                        } else {
                            return LMReturn::Error('无效的操作，不是草稿无法修改');
                        }
                    } catch (\Throwable $th) {
                        DB::rollBack();
                        return LMReturn::Error('操作失败');
                    }
                }
            } else {
                // 查看
                $data_list = [];
                if (empty($all['recode_id'])) {
                    $recodes = OaRecord::where('submit_id', $operation_id)->with('oa_flow.oa_model')->with('worker')->where('level', 1)->get();
                    foreach ($recodes as $recode) {
                        $data_dics = [];
                        $data_dics['recode_id'] = $recode->id;
                        $data_dics['level'] = $recode->level;
                        $data_dics['oa_flow_id'] = $recode->oa_flow_id;
                        $data_dics['worker_id'] = $recode->worker_id ?? '';
                        $data_dics['worker_name'] = $recode['worker']['name'];
                        $data_dics['model_name'] = $recode['oa_flow']['oa_model']['name'];
                        $data_dics['content'] = $recode->content;
                        $data_dics['remark'] = $recode->remark;
                        $data_dics['is_finally'] = $recode->is_finally;
                        $data_dics['is_pass'] = $recode->is_pass;
                        $data_dics['type'] = $recode->oa_flow->type;
                        $data_dics['money'] = $recode->families_money_record->money ?? 0;
                        $data_list[] = $data_dics;
                    }
                    $size = $all['size'] ?? 15;
                    $page = $all['page'] ?? 1;
                    $start = ($page - 1) * $size;
                    $article = array_slice($data_list, $start, $size);
                    $datas_list = [];
                    $count = count($data_list);
                    $datas_list['total'] = $count;
                    $datas_list['data'] = $article;
                    return LMReturn::Success($datas_list);
                } else {
                    $recode = OaRecord::where('id', $all['recode_id'])->with('oa_flow.oa_model')->with('worker')->first();
                    if ($recode) {
                        $datas_dic = [];
                        $datas_dic['level'] = $recode->level;
                        $datas_dic['oa_flow_id'] = $recode->oa_flow_id;
                        $datas_dic['worker_id'] = $recode->worker_id ?? '';
                        $datas_dic['worker_name'] = $recode['worker']['name'];
                        $datas_dic['model_name'] = $recode['oa_flow']['oa_model']['name'];
                        $datas_dic['content'] = $recode->content;
                        $datas_dic['remark'] = $recode->remark;
                        $datas_dic['is_pass'] = $recode->is_pass;
                        $datas_dic['type'] = $recode->oa_flow->type;
                        $datas_dic['money'] = $recode->families_money_record->money ?? 0;
                        $data_list[] = $datas_dic;
                        $flow_recodes = OaRecord::where('p_id', $recode->id)->with('oa_flow.oa_model')->with('worker')->get();
                        foreach ($flow_recodes as $flows) {
                            $data_dic = [];
                            $data_dic['level'] = $flows->level;
                            $data_dic['oa_flow_id'] = $flows->oa_flow_id;
                            $data_dic['worker_id'] = $flows->worker_id ?? '';
                            $data_dic['worker_name'] = $flows['worker']['name'];
                            $data_dic['model_name'] = $flows['oa_flow']['oa_model']['name'];
                            $data_dic['content'] = $flows->content;
                            $data_dic['remark'] = $flows->remark;
                            $data_dic['is_pass'] = $flows->is_pass;
                            $data_dic['type'] = $flows->oa_flow->type;
                            $data_dic['money'] = $flows->families_money_record->money ?? 0;
                            $data_list[] = $data_dic;
                        }
                        return LMReturn::Success($data_list);
                    } else {
                        return LMReturn::Error('未找到该流程');
                    }
                }
            }
        }
    }

    // 通过草稿提出申请，申请时先调此接口返回记录id
    public function OAdraft(Request $request)
    {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $operation_id = $tokenInfo['worker_id'];
        $all = $request->all();
        if ($all['oa_model_id']) {
            $oa_model_id = $all['oa_model_id'];
            $oa_flow = OaFlow::where('level', 1)->where('oa_model_id', $oa_model_id)->first();
            if (empty($oa_flow)) {
                return LMReturn::Error('该模板没有流程');
            }
            $record = OaRecord::where('submit_id', $operation_id)->where('is_finally', 4)->where('oa_flow_id', $oa_flow->id)->with('families_money_record')->first();
            if (isset($record)) {
                $data_dic['is_have'] = 1;
                $data_dic['record_id'] = $record->id;
                $data_dic['money'] = $record['families_money_record']['money'];
                $data_dic['remark'] = $record['remark'];
            } else {
                $data_dic['is_have'] = 2;
            }
            return LMReturn::Success($data_dic);
        } else {
            return LMReturn::Error('未传入模板');
        }
    }

    // 审核流程--审核--审批人
    public function OAaudit(Request $request)
    {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $operation_id = $tokenInfo['worker_id'];
        $worker = Worker::find($operation_id)
            ->with('branchesManage')
            ->first();
        $all = $request->all();
        if (empty($all['model'])) {
            return LMReturn::Error('未传入操作模式');
        } else {
            if ($all['model'] == 1) {
                // 审核
                if (empty($all['record_id'])) {
                    return LMReturn::updateErr('未传入审核记录id');
                } else {
                    $recode = OaRecord::where('id', $all['record_id'])->with('oa_flow')->first();
                    if (isset($recode)) {
                        $worker_id = $recode['oa_flow']['worker_id'];
                        if ($worker_id == $operation_id and $recode['is_pass'] == 0) {
                            DB::beginTransaction();
                            try {
                                if (empty($all['is_pass'])) {
                                    return LMReturn::updateErr('未传入审核结果');
                                } else {
                                    $is_pass = $all['is_pass'] == 1 ? 1 : 2;
                                }
                                $recode->is_pass = $is_pass;
                                $recode->content = $all['content'] ?? '';
                                $recode->save();
                                if ($is_pass == 1) {
                                    $this->get_next_flow($all['record_id'], $recode->level + 1);
                                } else {
                                    // 拒绝后修改FamiliesMoneyRecord状态
                                    $recodes = OaRecord::find($recode->p_id ?? $recode->id);
                                    $recodes->is_finally = 3;
                                    $recodes->save();
                                    if ($recode->finance_id) {
                                        $finances = FamiliesMoneyRecord::find($recode->finance_id);
                                        $finances->status = 3;
                                        $finances->save();
                                    }
                                    if ($recodes->massage_change_id) {
                                        $changes = MassageChangeRecord::find($recodes->massage_change_id);
                                        $changes->is_pass = 2;
                                        $changes->save();
                                    }
                                }
                            } catch (\Throwable $th) {
                                DB::rollback();             // 数据库回滚
                                return LMReturn::updateErr('当前网络访问量过大，请稍后查看');
                            }
                            DB::commit();
                            return LMReturn::Success();
                        } else {
                            return LMReturn::updateErr('您没有审核权限或改内容暂时无法审核');
                        }
                    } else {
                        return LMReturn::updateErr('未找到该审核记录');
                    }
                }
            } else {
                if (isset($all['record_id'])) {
                    $recodes = OaRecord::where('id', $all['record_id'])->with('oa_flow.oa_model.branches.manage_workers')->first();
                    if (isset($recodes)) {
                        //                        $sta = 0;
                        //                        if ($recodes->is_pass == 3 and $recodes->worker_id == $operation_id) {
                        //                            $sta = 1;
                        //                        } else {
                        //                            if ($recodes) {
                        //                                foreach ($recodes['oa_flow']['oa_model']['branches'] as $branchs) {
                        //                                    foreach ($branchs['manage_workers'] as $workers) {
                        //                                        if ($workers['id'] == $operation_id) {
                        //                                            $sta = 1;
                        //                                            break;
                        //                                        }
                        //                                    }
                        //                                    if ($sta == 1) {
                        //                                        break;
                        //                                    }
                        //                                }
                        //                            }
                        //                        }
                        //                        if ($sta == 0) {
                        //                            return LMReturn::selectErr('抱歉，您没有权限查看全部流程');
                        //                        } else {
                        $recode_top = OaRecord::where('id', $recodes->p_id ?? $recodes->id)->with('submit')->with('worker')->with('families_money_record')->with('massage_change_record.user')->with('massage_change_record.order.user')->with('massage_change_record.order.worker')->with('oa_flow.oa_model')->with('massage_change_record.bank_card.images')->with('massage_change_record.bank_card.user')->with('massage_change_record.old_bank_card.images')->first();
                        $sub_dic['worker_name'] = $recode_top['submit']['name'];
                        if ($recode_top['families_money_record']) {
                            $sub_dic['money'] = $recode_top['families_money_record']['money'];
                        }
                        $sub_dic['model_group'] = $recode_top['oa_flow']['oa_model']['group'];
                        $sub_dic['remark'] = $recode_top['remark'];
                        $sub_dic['type'] = 5;
                        $sub_dic['record_type'] = $recode_top['massage_change_record']['record_type'];
                        if ($recode_top['oa_flow']['oa_model']['group'] == 2) {
                            if ($recode_top['massage_change_id']) {
                                $up_date = [];
                                // 修改客户信息
                                if ($recode_top['massage_change_record']['record_type'] == 1) {
                                    $up_date['modify_obj'] = $recode_top['massage_change_record']['user']['name'];
                                    $up_date['modify_obj_id_num'] = $recode_top['massage_change_record']['user']['id_number'];
                                    if ($recode_top['massage_change_record']['id_type']) {
                                        $up_date['old_id_type'] = $recode_top['massage_change_record']['old_id_type'];
                                        $up_date['new_id_type'] = $recode_top['massage_change_record']['id_type'];
                                    }
                                    if ($recode_top['massage_change_record']['img_card_id']) {
                                        $up_date['new_img_card_id'] = $recode_top['massage_change_record']['img_card_id'];
                                        $up_date['old_img_card_id'] = $recode_top['massage_change_record']['old_img_card_id'];
                                    }
                                    if ($recode_top['massage_change_record']['user_name']) {
                                        $up_date['new_user_name'] = $recode_top['massage_change_record']['user_name'];
                                        $up_date['old_user_name'] = $recode_top['massage_change_record']['old_user_name'];
                                    }
                                    if ($recode_top['massage_change_record']['new_address']) {
                                        $up_date['new_address'] = $recode_top['massage_change_record']['new_address'];
                                        $up_date['old_address'] = $recode_top['massage_change_record']['old_address'];
                                    }
                                    if ($recode_top['massage_change_record']['count_num']) {
                                        $up_date['new_count_num'] = $recode_top['massage_change_record']['count_num'];
                                        $up_date['old_count_num'] = $recode_top['massage_change_record']['old_count_num'];
                                    }
                                    if ($recode_top['massage_change_record']['phone_num']) {
                                        $up_date['new_phone_num'] = $recode_top['massage_change_record']['phone_num'];
                                        $up_date['old_phone_num'] = $recode_top['massage_change_record']['old_phone_num'];
                                    }
                                    if ($recode_top['massage_change_record']['address_code']) {
                                        $new_areacode = $recode_top['massage_change_record']['address_code'];
                                        $old_areacode = $recode_top['massage_change_record']['old_address_code'];
                                        $new_address = CustArea::where('area_code', $new_areacode)->first();
                                        $old_address = CustArea::where('area_code', $old_areacode)->first();
                                        if (isset($new_address) && isset($old_address)) {
                                            $up_date['new_address_code'] = $new_address->area_fullname;
                                            $up_date['old_address_code'] = $old_address->area_fullname;
                                        }
                                    }
                                    if ($recode_top['massage_change_record']['new_email']) {
                                        $up_date['new_email'] = $recode_top['massage_change_record']['new_email'];
                                        $up_date['old_email'] = $recode_top['massage_change_record']['old_email'];
                                    }
                                    $up_date['status'] = $recode_top['massage_change_record']['is_pass'];
                                    if ($recode_top['massage_change_record']['img_id_list']) {
                                        if ($recode_top['massage_change_record']['is_pass'] == 3 || $recode_top['massage_change_record']['is_pass'] == 2) {
                                            $new_img_list_str = $recode_top['massage_change_record']['img_id_list'];
                                            $old_img_list_str = $recode_top['massage_change_record']['old_img_id_list'];
                                            $new_img_list = explode('-', $new_img_list_str);
                                            $old_img_list = explode('-', $old_img_list_str);
                                            $new_images = Image::whereIn('id', $new_img_list)->get();
                                            $old_images = Image::whereIn('id', $old_img_list)->get();
                                            $up_date['new_img_list'] = $new_images;
                                            $up_date['old_img_list'] = $old_images;
                                        } elseif ($recode_top['massage_change_record']['is_pass'] == 1) {
                                            $new_img_list_str = $recode_top['massage_change_record']['img_id_list'];
                                            $new_img_list = explode('-', $new_img_list_str);
                                            $new_images = Image::whereIn('id', $new_img_list)->get();
                                            $up_date['new_img_list'] = $new_images;
                                        }
                                    }
                                    $sub_dic['up_status'] = $up_date;
                                } elseif ($recode_top['massage_change_record']['record_type'] == 2) {
                                    // 修改银行卡号
                                    $up_date['order_id'] = $recode_top['massage_change_record']['order_id'];
                                    $up_date['contract_no'] = $recode_top['massage_change_record']['order']['contract_no'];
                                    $up_date['order_no'] = $recode_top['massage_change_record']['order']['order_no'];
                                    $up_date['user_name'] = $recode_top['massage_change_record']['order']['user']['name'];
                                    $up_date['user_id_number'] = $recode_top['massage_change_record']['order']['user']['id_number'];
                                    $up_date['old_bank_card'] = $recode_top['massage_change_record']['old_bank_card'];
                                    $up_date['new_bank_card'] = $recode_top['massage_change_record']['bank_card'];
                                    // 以下三条对完接口前端更新后删掉
                                    $up_date['order_data'] = $recode_top['massage_change_record']['order'];
                                    $up_date['old_bank_card_num'] = $recode_top['massage_change_record']['old_img_card_id'];
                                    $up_date['new_bank_card_num'] = $recode_top['massage_change_record']['img_card_id'];
                                    // ************************
                                    $sub_dic['up_status'] = $up_date;
                                } elseif ($recode_top['massage_change_record']['record_type'] == 3) {
                                    // 修改银行卡信息
                                    $up_date['user_name'] = $recode_top['massage_change_record']['bank_card']['user']['name'];
                                    $up_date['user_id_number'] = $recode_top['massage_change_record']['bank_card']['user']['id_number'];
                                    $up_date['bank_card_id'] = $recode_top['massage_change_record']['bank_card_id'];
                                    $up_date['status'] = $recode_top['massage_change_record']['is_pass'];
                                    if ($recode_top['massage_change_record']['img_id_list']) {
                                        if ($recode_top['massage_change_record']['is_pass'] == 3 || $recode_top['massage_change_record']['is_pass'] == 2) {
                                            $new_img_list_str = $recode_top['massage_change_record']['img_id_list'];
                                            $old_img_list_str = $recode_top['massage_change_record']['old_img_id_list'];
                                            $new_img_list = explode('-', $new_img_list_str);
                                            $old_img_list = explode('-', $old_img_list_str);
                                            $new_images = Image::whereIn('id', $new_img_list)->get();
                                            $old_images = Image::whereIn('id', $old_img_list)->get();
                                            $up_date['new_img_list'] = $new_images;
                                            $up_date['old_img_list'] = $old_images;
                                        } elseif ($recode_top['massage_change_record']['is_pass'] == 1) {
                                            $new_img_list_str = $recode_top['massage_change_record']['img_id_list'];
                                            $new_img_list = explode('-', $new_img_list_str);
                                            $new_images = Image::whereIn('id', $new_img_list)->get();
                                            $up_date['new_img_list'] = $new_images;
                                        }
                                    }
                                    if ($recode_top['massage_change_record']['id_type']) {
                                        $up_date['old_bank_id'] = $recode_top['massage_change_record']['old_id_type'];
                                        $up_date['new_bank_id'] = $recode_top['massage_change_record']['id_type'];
                                    }
                                    if ($recode_top['massage_change_record']['user_name']) {
                                        $up_date['new_account_name'] = $recode_top['massage_change_record']['user_name'];
                                        $up_date['old_account_name'] = $recode_top['massage_change_record']['old_user_name'];
                                    }
                                    if ($recode_top['massage_change_record']['count_num']) {
                                        $up_date['new_count_num'] = $recode_top['massage_change_record']['count_num'];
                                        $up_date['old_count_num'] = $recode_top['massage_change_record']['old_count_num'];
                                    }
                                    if ($recode_top['massage_change_record']['new_address']) {
                                        $up_date['new_bank_sum'] = $recode_top['massage_change_record']['new_address'];
                                        $up_date['old_bank_sum'] = $recode_top['massage_change_record']['old_address'];
                                    }
                                    $sub_dic['up_status'] = $up_date;
                                }
                            } else {
                                return LMReturn::Error('该记录不完整');
                            }
                        }
                        $data_list[] = $sub_dic;
                        $datas_dic = [];
                        $datas_dic['id'] = $recode_top->id;
                        $datas_dic['level'] = $recode_top->level;
                        $datas_dic['oa_flow_id'] = $recode_top->oa_flow_id;
                        $datas_dic['worker_id'] = $recode_top->worker_id ?? '';
                        $datas_dic['worker_name'] = $recode_top['worker']['name'];
                        $datas_dic['model_name'] = $recode_top['oa_flow']['oa_model']['name'];
                        $datas_dic['model_group'] = $recode_top['oa_flow']['oa_model']['group'];
                        $datas_dic['content'] = $recode_top->content;
                        $datas_dic['remark'] = $recode_top->remark;
                        $datas_dic['is_pass'] = $recode_top->is_pass;
                        $datas_dic['type'] = $recode_top->oa_flow->type;
                        if ($recode_top->families_money_record) {
                            $datas_dic['money'] = $recode_top->families_money_record->money;
                        }
                        $datas_dic['update_time'] = date('Y-m-d H:i:s', strtotime($recode_top->update_time));
                        $data_list[] = $datas_dic;
                        $flow_recodes = OaRecord::where('p_id', $recode_top->id)->with('worker')->with('oa_flow.oa_model')->get();
                        foreach ($flow_recodes as $flows) {
                            $data_dic = [];
                            $data_dic['id'] = $flows->id;
                            $data_dic['level'] = $flows->level;
                            $data_dic['oa_flow_id'] = $flows->oa_flow_id;
                            $data_dic['worker_id'] = $flows->worker_id ?? '';
                            $data_dic['worker_name'] = $flows['worker']['name'];
                            $data_dic['model_name'] = $flows['oa_flow']['oa_model']['name'];
                            $data_dic['model_group'] = $flows['oa_flow']['oa_model']['group'];
                            $data_dic['content'] = $flows->content;
                            $data_dic['remark'] = $flows->remark;
                            $data_dic['is_pass'] = $flows->is_pass;
                            $data_dic['type'] = $flows->oa_flow->type;
                            if ($recode_top->families_money_record) {
                                $data_dic['money'] = $flows->families_money_record->money;
                            }
                            $data_dic['update_time'] = date('Y-m-d H:i:s', strtotime($flows->update_time));
                            $data_list[] = $data_dic;
                        }
                        return LMReturn::Success($data_list);
                        //                        }
                    } else {
                        return LMReturn::Error('没有该记录');
                    }
                }
                // 查看
                $is_child = $all['is_child'] ?? 1;      //  为1是看审核全部的，2是看审核直属部门的，3是只看自己审批的
                $is_cc = $all['is_cc'] ?? 1;         //  1有抄送， 2无抄送， 3只看抄送， 4只看待审核， 5只看通过， 6只看拒绝
                switch ($is_cc) {
                    case 2:
                        $num = [0, 1, 2];
                        break;
                    case 3:
                        $num = [3];
                        break;
                    case 4:
                        $num = [0];
                        break;
                    case 5:
                        $num = [1];
                        break;
                    case 6:
                        $num = [2];
                        break;
                    default:
                        $num = [0, 1, 2, 3];
                        break;
                }
                $branch_manage_list = $worker->branchesManage;
                $branch_list = [];
                if (count($branch_manage_list) > 0) {
                    $branch_dic = BranchUtils::getAllBranchs();
                    foreach ($branch_manage_list as $m_branch) {
                        $branch_list[] = $m_branch['id'];
                        $branch_list = BranchUtils::getChildBranchs($m_branch['id'], $branch_dic, $branch_list);
                    }
                }
                $branch_id = $branch_manage_list[0]['id'];
                $oa_record_list = OaRecord::when(count($branch_list) > 0, function ($query) use ($branch_list, $num) {
                    return $query->where('is_pass', '!=', 4)->where('is_pass', '!=', 5)->whereIn('branch_id', $branch_list)->whereIn('is_pass', $num);
                })
                    ->when(count($branch_list) == 0, function ($query) use ($operation_id, $num) {
                        return $query->where('worker_id', $operation_id)->where('is_pass', '!=', 4)->where('is_pass', '!=', 5)->whereIn('is_pass', $num);
                    })
                    ->when($is_child == 2, function ($query) use ($branch_id, $num) {
                        return $query->where('branch_id', $branch_id)->where('is_pass', '!=', 4)->where('is_pass', '!=', 5)->whereIn('is_pass', $num);
                    })
                    ->when($is_child == 3, function ($query) use ($operation_id, $num) {
                        return $query->where('worker_id', $operation_id)->where('is_pass', '!=', 4)->where('is_pass', '!=', 5)->whereIn('is_pass', $num);
                    })->with('oa_flow.oa_model')->with('families_money_record')->with('submit')->with('branch')->with('worker')
                    ->get();
                $oa_records = [];
                foreach ($oa_record_list as $oa_recode_dic) {
                    $oa_recorde_new = [];
                    $oa_recorde_new['id'] = $oa_recode_dic['id'];
                    $oa_recorde_new['level'] = $oa_recode_dic['level'];
                    $oa_recorde_new['oa_flow_id'] = $oa_recode_dic['oa_flow_id'];
                    $oa_recorde_new['worker_id'] = $oa_recode_dic['worker_id'];
                    $oa_recorde_new['worker_name'] = $oa_recode_dic['worker']['name'];
                    $oa_recorde_new['submit_id'] = $oa_recode_dic['submit_id'];
                    $oa_recorde_new['submit_name'] = $oa_recode_dic['submit']['name'];
                    $oa_recorde_new['branch_id'] = $oa_recode_dic['branch_id'];
                    $oa_recorde_new['branch_name'] = $oa_recode_dic['branch']['name'];
                    $oa_recorde_new['model_name'] = $oa_recode_dic['oa_flow']['oa_model']['name'];
                    $oa_recorde_new['model_group'] = $oa_recode_dic['oa_flow']['oa_model']['group'];
                    if ($oa_recode_dic['families_money_record']) {
                        $oa_recorde_new['money'] = $oa_recode_dic['families_money_record']['money'];
                    }
                    $oa_recorde_new['content'] = $oa_recode_dic['content'];
                    $oa_recorde_new['remark'] = $oa_recode_dic['remark'];
                    $oa_recorde_new['is_pass'] = $oa_recode_dic['is_pass'];
                    $oa_recorde_new['create_time'] = date('Y-m-d H:i:s', strtotime($oa_recode_dic['create_time']));
                    $oa_records[] = $oa_recorde_new;
                }
                $size = $all['size'] ?? 15;
                $page = $all['page'] ?? 1;
                $start = ($page - 1) * $size;
                $article = array_slice($oa_records, $start, $size);
                $datas_list = [];
                $count = count($oa_records);
                $datas_list['total'] = $count;
                $datas_list['data'] = $article;
                return LMReturn::Success($datas_list);
            }
        }
    }

    // OA记录查询接口
    public function getOArecords(Request $request)
    {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $operation_id = $tokenInfo['worker_id'];
        $all = $request->all();
        $record_type = $all['record_type'];
        $manage_branchs = Worker::where('id', $operation_id)->with('branchesManage')->first();
        if ($manage_branchs['branchesManage'] == []) {
            return LMReturn::Error('无权限');
        }
        $manage_branch_id = $manage_branchs['branchesManage'][0]['id'];
        $child_branchs = $this->getChildBranchs($manage_branch_id, $this->getAllBranchs(), [$manage_branch_id]);
        $oa_record_list = OaRecord::when($record_type == 1, function ($query) use ($operation_id) {
            return $query->where('is_pass', 0)->where('worker_id', $operation_id);
        })
            ->when($record_type == 2, function ($query) use ($operation_id) {
                return $query->where('worker_id', $operation_id)->whereIn('is_pass', [1, 2]);
            })
            ->when($record_type == 3, function ($query) use ($operation_id) {
                return $query->where('submit_id', $operation_id)->whereIn('is_finally', [1, 2, 3, 5]);
            })
            ->when($record_type == 4, function ($query) use ($operation_id) {
                return $query->where('worker_id', $operation_id)->where('is_pass', 3);
            })
            ->when($record_type == 5, function ($query) use ($child_branchs, $operation_id) {
                return $query->whereIn('branch_id', $child_branchs)->where('level', 1);
            })
            ->with('oa_flow.oa_model')->with('families_money_record')->with('submit')->with('branch')->with('worker')
            ->get();
        $oa_records = [];
        if ($record_type == 4) {
            $pid_list = [];
            foreach ($oa_record_list as $oa_recode_dic) {
                $pid_list[] = $oa_recode_dic['p_id'];
            }
            $oa_record_list = OaRecord::whereIn('id', array_unique($pid_list))->get();
        }
        foreach ($oa_record_list as $oa_recode_dic) {
            try {
                $oa_recorde_new = [];
                $oa_recorde_new['id'] = $oa_recode_dic['id'];
                $oa_recorde_new['level'] = $oa_recode_dic['level'];
                $oa_recorde_new['oa_flow_id'] = $oa_recode_dic['oa_flow_id'];
                $oa_recorde_new['worker_id'] = $oa_recode_dic['worker_id'];
                $oa_recorde_new['worker_name'] = $oa_recode_dic['worker']['name'];
                $oa_recorde_new['submit_id'] = $oa_recode_dic['submit_id'];
                $oa_recorde_new['submit_name'] = $oa_recode_dic['submit']['name'];
                $oa_recorde_new['branch_id'] = $oa_recode_dic['branch_id'];
                $oa_recorde_new['branch_name'] = $oa_recode_dic['branch']['name'];
                $oa_recorde_new['model_name'] = $oa_recode_dic['oa_flow']['oa_model']['name'];
                $oa_recorde_new['model_group'] = $oa_recode_dic['oa_flow']['oa_model']['group'];
                if ($oa_recode_dic['families_money_record']) {
                    $oa_recorde_new['money'] = $oa_recode_dic['families_money_record']['money'];
                }
                $oa_recorde_new['content'] = $oa_recode_dic['content'];
                $oa_recorde_new['remark'] = $oa_recode_dic['remark'];
                $oa_recorde_new['is_finally'] = $oa_recode_dic['is_finally'];
                $oa_recorde_new['is_pass'] = $oa_recode_dic['is_pass'];
                $oa_recorde_new['create_time'] = date('Y-m-d H:i:s', strtotime($oa_recode_dic['create_time']));
                $oa_records[] = $oa_recorde_new;
            } catch (\Throwable $th) {
            }
        }
        $size = $all['size'] ?? 15;
        $page = $all['page'] ?? 1;
        $start = ($page - 1) * $size;
        $article = array_slice($oa_records, $start, $size);
        $datas_list = [];
        $count = count($oa_records);
        $datas_list['total'] = $count;
        $datas_list['data'] = $article;
        return LMReturn::Success($datas_list);
    }

    // 客户信息申请修改接口
    public function updateUserMassage(Request $request)
    {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $operation_id = $tokenInfo['worker_id'];
        $operation = Worker::where('id', $operation_id)->with('branches')->first();
        if ($operation['branches'] == []) {
            return LMReturn::Error('您还没有归属部门');
        }
        $all = $request->all();
        if (isset($all['change_type'])) {
            $types = $all['change_type'];
        } else {
            return LMReturn::Error('未传入修改模式');
        }
        DB::beginTransaction();
        try {
            $stuts = 0;
            $new_Maggage_change = new MassageChangeRecord;
            $new_Maggage_change->is_pass = 3;
            if ($types == 1) {
                $new_Maggage_change->record_type = 1;
                if (empty($all['user_id'])) {
                    return LMReturn::Error('未传入客户id');
                }
                $massages = MassageChangeRecord::where('user_id', $all['user_id'])->where('record_type', 1)->where('is_pass', 3)->first();
                if (isset($massages)) {
                    return LMReturn::Error('已提交的审核暂未处理完成，不可重复提交，请稍后查看结果');
                }
                $user_id = $all['user_id'];
                $orders = Order::where('user_id', $user_id)->whereIn('order_status', [4, 6])->first();
                if (empty($orders)) {
                    return LMReturn::Error('该用户没有正在进行的订单信息，请直接点击确定修改');
                }
                if (isset($all['worker_id']) && $all['worker_id'] != '') {
                    if ($orders->worker_id != $all['worker_id']) {
                        return LMReturn::Error('已有生效订单，不允许修改客户经理');
                    }
                }
                $new_Maggage_change->user_id = $user_id;
                $user = User::where('id', $user_id)->with('images')->first();
                //                if ($user->worker_id != $operation_id) {
                //                    return LMReturn::Error('没有权限修改');
                //                }
                if ($user->branch_id == null) {
                    $oa_branch = $operation['branches'][0]['id'];
                } else {
                    $oa_branch = $user->branch_id;
                }
                if (empty($user)) {
                    return LMReturn::Error('没有该用户信息');
                }
                if (isset($all['img_id_list'])) {
                    $image_list = Image::whereIn('id', $all['img_id_list'])->whereIn('img_type', [1, 2])->get();
                    if (count($image_list) == count($all['img_id_list'])) {
                        $user_image_ids = [];
                        $user_images = Image::where('user_id', $user_id)->whereIn('img_type', [1, 2])->get();
                        $old_image_id_str = '';
                        if (count($user_images) > 0) {
                            foreach ($user_images as $image) {
                                $user_image_ids[] = $image['id'];
                            }
                            $old_image_id_str = join('-', $user_image_ids);
                        }
                        $image_id_str = join('-', $all['img_id_list']);
                        if ($old_image_id_str != $image_id_str) {
                            if ($old_image_id_str) {
                                $new_Maggage_change->old_img_id_list = $old_image_id_str;
                            }
                            if ($image_id_str) {
                                $new_Maggage_change->img_id_list = $image_id_str;
                            }
                        }
                    } else {
                        return LMReturn::Error('存在无效图片id，请检查数据');
                    }
                }
                if (isset($all['img_card_id']) && $all['img_card_id'] != '') {
                    if ($user->id_number != $all['img_card_id']) {
                        $stuts = 1;
                        $new_Maggage_change->old_img_card_id = $user->id_number;
                        $new_Maggage_change->img_card_id = $all['img_card_id'];
                    }
                }
                if (isset($all['phone_num']) && $all['phone_num'] != '') {
                    if ($user->contact_manner != $all['phone_num']) {
                        $stuts = 1;
                        $new_Maggage_change->old_phone_num = $user->contact_manner;
                        $new_Maggage_change->phone_num = $all['phone_num'];
                    }
                }
                if (isset($all['email']) && $all['email'] != '') {
                    if ($user->email != $all['email']) {
                        $stuts = 1;
                        $new_Maggage_change->old_email = $user->email;
                        $new_Maggage_change->new_email = $all['email'];
                    }
                }
                if (isset($all['address']) && $all['address'] != '') {
                    if ($user->address != $all['address']) {
                        $stuts = 1;
                        $new_Maggage_change->old_address = $user->address;
                        $new_Maggage_change->new_address = $all['address'];
                    }
                }
                if (isset($all['user_name']) && $all['user_name'] != '') {
                    if ($user->name != $all['user_name']) {
                        $stuts = 1;
                        $new_Maggage_change->old_user_name = $user->name;
                        $new_Maggage_change->user_name = $all['user_name'];
                    }
                }
                if (isset($all['count_num']) && $all['count_num'] != '') {
                    if ($user->account != $all['count_num']) {
                        $stuts = 1;
                        $new_Maggage_change->old_count_num = $user->account;
                        $new_Maggage_change->count_num = $all['count_num'];
                    }
                }
                if (isset($all['id_type']) && $all['id_type'] != '') {
                    if ($user->id_type != $all['id_type']) {
                        $stuts = 1;
                        $new_Maggage_change->old_id_type = $user->id_type;
                        $new_Maggage_change->id_type = $all['id_type'];
                    }
                }
                if (isset($all['address_code']) && $all['address_code'] != '') {
                    if ($user->area_code != $all['address_code']) {
                        $stuts = 1;
                        $new_Maggage_change->old_address_code = $user->area_code;
                        $new_Maggage_change->address_code = $all['address_code'];
                    }
                }
                if ($stuts == 0) {
                    DB::rollBack();
                    return LMReturn::Error('并无修改内容,或只修改图片无需审核');
                } else {
                    $new_Maggage_change->save();
                }
            } elseif ($types == 3) {
                if (isset($all['bank_card_id'])) {
                    $bank_card = BankCard::where('id', $all['bank_card_id'])->with('images')->first();
                    if ($bank_card) {
                        $bank_id = $bank_card->bank_id;
                        $bank_num = $bank_card->bank_num;
                        $bank_sum_name = $bank_card->bank_sum_name;
                        $account_name = $bank_card->account_name;
                        $bank_card_images = [];
                        if (count($bank_card->images) > 0) {
                            foreach ($bank_card->images as $image) {
                                $bank_card_images[] = $image['id'];
                            }
                        }
                        $new_Maggage_change->record_type = 3;
                        if (isset($all['img_id_list'])) {
                            $image_list = Image::whereIn('id', $all['img_id_list'])->whereIn('img_type', [1, 2])->get();
                            if (count($image_list) == count($all['img_id_list'])) {
                                $old_image_id_str = '';
                                if (count($bank_card_images) > 0) {
                                    $old_image_id_str = join('-', $bank_card_images);
                                }
                                $image_id_str = join('-', $all['img_id_list']);
                                if ($old_image_id_str != $image_id_str) {
                                    if ($old_image_id_str) {
                                        $new_Maggage_change->old_img_id_list = $old_image_id_str;
                                    }
                                    if ($image_id_str) {
                                        $new_Maggage_change->img_id_list = $image_id_str;
                                    }
                                }
                            } else {
                                return LMReturn::Error('存在无效图片id，请检查数据');
                            }
                        }
                        if (isset($all["bank_id"])) {
                            if ($all["bank_id"] != $bank_id) {
                                $stuts = 1;
                                $new_Maggage_change->old_id_type = $bank_id;
                                $new_Maggage_change->id_type = $all["bank_id"];
                            }
                        }
                        if (isset($all["bank_num"])) {
                            if ($all["bank_num"] != $bank_num) {
                                $stuts = 1;
                                $new_Maggage_change->old_count_num = $bank_num;
                                $new_Maggage_change->count_num = $all["bank_num"];
                            }
                        }
                        if (isset($all["bank_sum_name"])) {
                            if ($all["bank_sum_name"] != $bank_sum_name) {
                                $stuts = 1;
                                $new_Maggage_change->old_address = $bank_sum_name;
                                $new_Maggage_change->new_address = $all["bank_sum_name"];
                            }
                        }
                        if (isset($all["account_name"])) {
                            if ($all["account_name"] != $account_name) {
                                $stuts = 1;
                                $new_Maggage_change->old_user_name = $account_name;
                                $new_Maggage_change->user_name = $all["account_name"];
                            }
                        }
                        if ($stuts == 0) {
                            DB::rollBack();
                            return LMReturn::Error('并无修改内容,或只修改图片无需审核');
                        } else {
                            $new_Maggage_change->save();
                        }
                    } else {
                        return LMReturn::Error('请传入正确的银行卡id');
                    }
                } else {
                    return LMReturn::Error('为传入银行卡id');
                }
            } else {
                $new_Maggage_change->record_type = 2;
                if (empty($all['order_id'])) {
                    return LMReturn::Error('未传入订单id');
                }
                $massages = MassageChangeRecord::where('order_id', $all['order_id'])->where('record_type', 2)->where('is_pass', 3)->first();
                if (isset($massages)) {
                    return LMReturn::Error('已提交的审核暂未处理完成，不可重复提交，请稍后查看结果');
                }
                $order_id = $all['order_id'];
                $new_Maggage_change->order_id = $order_id;
                $order = Order::where('id', $order_id)->whereIn('order_status', [4, 6])->with('bank_card')->with('user.bank_cards')->first();
                $oa_branch = $order->branch_id;
                if (empty($order)) {
                    return LMReturn::Error('没有该订单， 或该订单暂未生效，可直接修改银行卡');
                }
                if (isset($all['bank_card_id']) && $all['bank_card_id'] != '') {
                    if ($all['bank_card_id'] == $order->bank_card_id) {
                        return LMReturn::Error('无修改内容，无需进行审核');
                    }
                    $sta = 0;
                    foreach ($order['user']['bank_cards'] as $bank_card) {
                        if ($bank_card['id'] == $all['bank_card_id']) {
                            $new_Maggage_change->old_bank_card_id = $order->bank_card_id;
                            $new_Maggage_change->bank_card_id = $all['bank_card_id'];
                            $new_Maggage_change->old_img_card_id = $order['bank_card']['bank_num'];
                            $new_Maggage_change->img_card_id = $bank_card['bank_num'];
                            $new_Maggage_change->save();
                            $sta = 1;
                            break;
                        }
                    }
                    if ($sta == 0) {
                        return LMReturn::Error('无法修改，该订单没有此银行卡');
                    }
                } else {
                    return LMReturn::Error('未选择银行卡');
                }
            }
            // 已创建记录，开启OA审核
            $top_branch = Branch::where('pid', 0)->first();
            if ($oa_branch == $top_branch->id) {
                $oa_models = OaModel::where('group', 2)->orderBy('oa_model.id', 'asc')->get();
                $oa_model_id = $oa_models[0]['id'];
            } else {
                $branch_list = BranchUtils::getBranchChain($oa_branch);
                $oa_models = OaModel::where('group', 2)->with('branches')->get();
                $oa_model = null;
                foreach ($oa_models as $aoa_model) {
                    if ($aoa_model['branches'] != []) {
                        foreach ($aoa_model['branches'] as $branch) {
                            if (in_array($branch['id'], $branch_list)) {
                                $oa_model = $aoa_model;
                                break;
                            }
                        }
                        if ($oa_model != null) {
                            break;
                        }
                    }
                }
                if ($oa_model == null) {
                    return LMReturn::Error('没有该功能模板，请先创建');
                } else {
                    $oa_model_id = $oa_model['id'];
                }
            }
            if ($types == 1) {
                $remark = '客户信息修改申请';
            } elseif ($types == 2) {
                $remark = '已生效订单修改银行卡申请';
            } else {
                $remark = '银行卡信息修改申请';
            }
            $flow = OaFlow::where('oa_model_id', $oa_model_id)->where('level', 1)->first();
            if (empty($flow)) {
                DB::rollBack();
                return LMReturn::Error('暂未创建模板，无法提出申请');
            }
            $new_recode_id = $this->create_all_record($flow->id, $remark, $operation_id, $operation['branches'][0]['id'], 1, 4, null, null, $new_Maggage_change->id);
            $recodes = OaRecord::where('id', $new_recode_id)->with('oa_flow')->first();
            $recodes->is_finally = 2;
            if ($recodes['oa_flow']['type'] == 2) {
                $recodes->is_pass = 3;
                $recodes->save();
                $this->get_next_flow($new_recode_id, 2);
            } elseif ($recodes['oa_flow']['type'] == 1) {
                $recodes->is_pass = 0;
                $recodes->save();
            }
        } catch (\Throwable $th) {
            DB::rollBack();
            return LMReturn::Error('添加失败');
        }
        DB::commit();
        return LMReturn::Success();
    }

    // 撤销申请
    public function undoOArecord(Request $request)
    {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $operation_id = $tokenInfo['worker_id'];
        $all = $request->all();
        $record_id = $all['record_id'];
        $record = OaRecord::where('id', $record_id)->with('families_money_record')->first();
        if (isset($record)) {
            if ($record->submit_id != $operation_id) {
                return LMReturn::Error('无法撤销');
            }
            $record->is_pass = 4;
            $record->is_finally = 5;
            $record->save();
            OaRecord::where('p_id', $record_id)->delete();
            FamiliesMoneyRecord::where('id', $record->finance_id)->update(['status' => 3]);
            return LMReturn::Success();
        } else {
            return LMReturn::Error('无该条记录');
        }
    }

    /***以下是方法***/

    // 查找所有部门并且按照上级部门整理好array
    public static  function getAllBranchs()
    {
        $branchs = Branch::where('is_effective', 1)->orderBy('branch.pid', 'asc')->get();
        $branchs_dics = [];
        $pid_list = [];
        foreach ($branchs as $branch) {
            $branch_dic = [];
            $branch_dic['id'] = $branch->id;
            $branch_dic['name'] = $branch->name;
            $branch_dic['pid'] = $branch->pid;
            $branch_dic['hid'] = $branch->hid;
            if (empty($branchs_dics[$branch->pid])) {
                $new_list = [];
                foreach ($pid_list as $pid_dic) {
                    if ($pid_dic['hid'] == null) {
                        $top_id = $pid_dic['id'];
                        $new_list[] = $pid_dic;
                        $last_pid = $pid_list[0]['pid'];
                        $branchs_dics[$last_pid] = Utils::getArrayHid($new_list, $pid_list, $top_id);
                        break;
                    }
                }
                $pid_list = [];
            }
            $pid_list[] = $branch_dic;
            $branchs_dics[$branch->pid] = $pid_list;
        }
        return $branchs_dics;
    }

    // 查找单个部门子部门
    public static function  getChildBranchs($branch_id, $branchs_dics, $child_branchs)
    {
        if (isset($branchs_dics[$branch_id])) {
            foreach ($branchs_dics[$branch_id] as $branch) {
                $child_branchs[] = $branch['id'];
                $child_branchs = OAController::getChildBranchs($branch['id'], $branchs_dics, $child_branchs);
            }
        }
        return $child_branchs;
    }

    // 查找部门部门的所有上级部门
    public function getParentBranchs($branch_id, $branchs_dics, $parent_branchs)
    {
        foreach ($branchs_dics as $branch) {
            if ($branch['id'] == $branch_id) {
                if ($branch['pid'] != 0) {
                    $parent_branchs[] = $branch['pid'];
                    return $this->getParentBranchs($branch['pid'], $branchs_dics, $parent_branchs);
                } else {
                    return $parent_branchs;
                }
            }
        }
        return $parent_branchs;
    }

    // 抄送进到下一个，直到审核为止
    public function get_next_flow($recode_id, $level)
    {
        $recodes = OaRecord::where('p_id', $recode_id)->where('level', $level)->with('oa_flow')->first();
        if (isset($recodes)) {
            if ($recodes['oa_flow']['type'] == '2') {
                $recodes->is_pass = 3;
                $recodes->save();
                $this->get_next_flow($recode_id, $level + 1);
            } elseif ($recodes['oa_flow']['type'] == '1') {
                $recodes->is_pass = 0;
                $recodes->save();
            }
        } else {
            // 全部通过后修改FamiliesMoneyRecord状态
            $p_ids = OaRecord::find($recode_id);
            $p_id = $p_ids->p_id ?? $p_ids->id;
            $recodes = OaRecord::find($p_id);
            $recodes->is_finally = 1;
            $recodes->save();
            if ($recodes->finance_id) {
                $finances = FamiliesMoneyRecord::find($recodes->finance_id);
                $finances->status = 2;
                $finances->save();
            }
            if ($recodes->massage_change_id) {
                $changes = MassageChangeRecord::find($recodes->massage_change_id);
                $changes->is_pass = 1;
                $changes->save();
                // 调用客户信息修改方法
                Utils::updateUserABankCard($recodes->massage_change_id);
            }
        }
    }

    // 创建所有待启用记录
    public function create_all_record($flow_id, $remark, $submit_id, $branch_id, $level, $is_pass, $finance_id = null, $p_id = null, $massage_change_id = null, $img1_id = null, $img2_id = null, $img3_id = null)
    {
        $flows = OaFlow::where('id', $flow_id)->first();
        $flow_recode = new OaRecord();
        if ($p_id) {
            $flow_recode->p_id = $p_id;
        }
        if ($massage_change_id) {
            $flow_recode->massage_change_id = $massage_change_id;
        }
        $flow_recode->level = $level;
        $flow_recode->oa_flow_id = $flow_id;
        $flow_recode->worker_id = $flows->worker_id;
        $flow_recode->submit_id = $submit_id;
        if ($finance_id) {
            $flow_recode->finance_id = $finance_id;
        }
        $flow_recode->branch_id = $branch_id;
        $flow_recode->remark = $remark;
        $flow_recode->is_pass = $is_pass;
        if ($img1_id) {
            $flow_recode->img1_id = $img1_id;
        }
        if ($img2_id) {
            $flow_recode->img2_id = $img2_id;
        }
        if ($img3_id) {
            $flow_recode->img3_id = $img3_id;
        }
        $flow_recode->save();
        if ($p_id) {
            $next_pid = $p_id;
        } else {
            $next_pid = $flow_recode->id;
        }
        $next_flows = OaFlow::where('p_id', $flow_id)->first();
        if ($next_flows) {
            $this->create_all_record($next_flows->id, $remark, $submit_id, $branch_id, $level + 1, $is_pass, $finance_id, $next_pid);
        }
        return $flow_recode->id;
    }

    // 流程查询
    public function sele_flow($data_list, $flow_id)
    {
        $flows = OaFlow::where('p_id', $flow_id)->with('oa_model')->with('worker.branches')->first();
        if (isset($flows)) {
            $data_dic = [];
            $data_dic['flows_id'] = $flows->id;
            $data_dic['worker_id'] = $flows->worker_id;
            $data_dic['worker_name'] = $flows['worker']['name'] ?? '';
            $data_dic['branch_id'] = $flows['worker']['branches'][0]['id'] ?? '';
            $data_dic['branch_name'] = $flows['worker']['branches'][0]['name'] ?? '';
            $data_dic['oa_model_id'] = $flows->oa_model_id;
            $data_dic['model_name'] = $flows['oa_model']['name'];
            $data_dic['model_group'] = $flows['oa_model']['group'];
            $data_dic['level'] = $flows->level;
            $data_dic['type'] = $flows->type;
            $data_dic['worker_type'] = $flows->worker_type;
            $data_list[] = $data_dic;
            $data_list = $this->sele_flow($data_list, $flows->id);
            return $data_list;
        } else {
            return $data_list;
        }
    }

    // 修改优先级方法$sta为1时+，2是-，用递归法
    public function up_level($sta, $flow_id)
    {
        $flows = OaFlow::find($flow_id);
        $level = $flows->level;
        if ($sta == 1) {
            $flows->level = $level + 1;
        } else {
            $flows->level = $level - 1;
        }
        $flows->save();
        $next_flow = OaFlow::where('p_id', $flow_id)->first();
        if (isset($next_flow)) {
            $this->up_level($sta, $next_flow->id);
        }
    }

    // 传入部门id，返回由上级至子级的部门树
    public function getBranchChain($branch_id)
    {
        $chain_branchs = $this->getChildBranchs($branch_id, $this->getAllBranchs(), [$branch_id]);
        $branchs = Branch::all();
        return $this->getParentBranchs($branch_id, $branchs, $chain_branchs);
    }
}
